//
//  IMUserAvatarImageView.m
//  MLIM
//
//  Created by molon on 15/7/6.
//  Copyright (c) 2015年 molon. All rights reserved.
//

#import "IMUserAvatarImageView.h"
#import "IMCommon.h"

@interface IMUserAvatarImageView()

@property (nonatomic, strong) IMUser *imUser;

@end

@implementation IMUserAvatarImageView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(imUserUpdated:) name:MLIM_IMUser_UpdateOrAddUsers_Notification object:nil];
        
        self.userInteractionEnabled = YES;
        [self addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapped)]];
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:MLIM_IMUser_UpdateOrAddUsers_Notification object:nil];
}


#pragma mark - notification
- (void)imUserUpdated:(NSNotification*)notification
{
    if ([NSString IsNilOrEmpty:self.clientId]) {
        return;
    }
    
    NSDictionary *dict = notification.userInfo[@"imUsers"];
    
    IMUser *imUser = dict[self.clientId];
    if (imUser) {
        self.imUser = imUser;
    }
}

#pragma mark - setter
- (void)setClientId:(NSString *)clientId
{
    _clientId = [clientId copy];
    
    [IMUM imUserWithClientId:clientId callback:^(IMUser *imUser, NSError *error) {
        if (error||!imUser) {
            //TODO:最好是发现需要向后端请求数据之前设置为nil。但是要在发现当前没有头像之后，防止下面的重复setImageWithURL，影响性能
            self.image = nil;
        }else{
            self.imUser = imUser;
        }
    }];
}

- (void)setImUser:(IMUser *)imUser
{
    _imUser = imUser;
    
    //没变的话就不刷新
    if (![imUser.avatarURL isEqual:self.sd_imageURL]||!self.image) {
        [self sd_setImageWithURL:imUser.avatarURL];
    }
}

#pragma mark - event
- (void)tapped
{
    if (self.didTappedAvatarBlock) {
        self.didTappedAvatarBlock(self.imUser);
    }
}
@end
